package com.shell.arouter.demo.download

import android.app.ProgressDialog
import android.content.Context
import android.util.Log
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.durian.base.frame.viewbinding.viewBindings
import com.durian.base.rxhttp.RxHttp
import com.durian.base.rxhttp.download.Android10DownloadFactory
import com.durian.base.rxhttp.exception.RxHttpResponseException
import com.durian.base.rxhttp.param.toDownload
import com.durian.base.update.XUpdate
import com.durian.base.update.proxy.impl.cancel
import com.durian.base.update.request
import com.durian.base.update.ui.LeadUpdateListener
import com.durian.base.utils.MD5
import com.durian.base.utils.NetUtils
import com.henanjianye.soon.communityo2o2.databinding.FragmentDownloadBinding
import com.shell.arouter.extend.PAHT_FRAGMENT_DOWANLOAD
import com.shell.arouter.extend.toast
import com.shell.arouter.extend.tryLaunch
import com.shell.arouter.ui.FragmentCommon
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import java.io.File
import java.net.ConnectException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException

/**
 * 说明：FragmentDownload
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2021/10/20 10:42 下午
 * <p/>
 * 版本：version 1.0
 */
@Route(path = PAHT_FRAGMENT_DOWANLOAD)
class FragmentDownload : FragmentCommon(){

    private val progressDialog by lazy {
        ProgressDialog(activity).apply {
            setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
            setCancelable(false)
            setTitle("下载")
            setButton("取消"){dialog, _ ->
                dialog?.dismiss()
                cancelDownload()
            }
            progress = 0
            max = 100
        }
    }
    private val viewBinding by viewBindings<FragmentDownloadBinding>()

    private val DOWNLOAD_URL = "http://update.9158.com/miaolive/Miaolive.apk?method=get&versionName=1.0.0"
//    private val DOWNLOAD_URL = "https://www.wanandroid.com/blogimgs/aa0da019-c965-4c8a-8919-198397e0c3f1.apk"

    override fun bindRootView(context: Context?): View {
        return viewBinding.root
    }

    override fun isShowTitleBar(): Boolean {
        return true
    }

    override fun isShowTitleBarBack(): Boolean {
        return true
    }

    override fun bindTitleBarText(): String? {
        return "下载"
    }

    override fun onFirstUserVisible() {
        super.onFirstUserVisible()
        viewBinding.btnDownload.setOnClickListener {
            download()
        }
        viewBinding.btnDownload10.setOnClickListener {
            download10()
        }
        viewBinding.btnDownloadAppend.setOnClickListener {
            downloadAppend()
        }
        viewBinding.btnDownload10Append.setOnClickListener {
            download10Append()
        }
        viewBinding.btnCancel.setOnClickListener {
            RxHttp.cancelTag(DOWNLOAD_URL)
        }
        viewBinding.btnUpdate.setOnClickListener {
            if (XUpdate.isDownloading()){
                XUpdate.cancel()
            }else{
                update()
            }
        }
        viewBinding.btnClearResult.setOnClickListener {
            viewBinding.tvResult.text = ""
        }
    }

    private var isUpdate = false

    private fun update(){
        XUpdate.request()
            .setUpdateListener(LeadUpdateListener.Config(this){
                it.showCheckLoading = false
                it.showNewVersionDialog = true
                it.showInstallDialog = false
                it.showDownloadLoading = true
                it.downloadDialogConfirmText = "后台下载"
            })
            .update(this)
    }

    private fun cancelDownload(){
        RxHttp.cancelTag(DOWNLOAD_URL)
    }
    private fun download(){
        scope.tryLaunch {
            val file = File(viewBinding.root.context.externalCacheDir,"${System.currentTimeMillis()}.apk")
            viewBinding.tvResult.append("---开始下载：${file.absolutePath}\n")
            progressDialog.show()
            RxHttp.get(DOWNLOAD_URL)
                .addParam("time",System.currentTimeMillis())
                .tag(DOWNLOAD_URL)
                .toDownload(file){
                    progressDialog.progress = it.progress
                    viewBinding.tvResult.append("progress-(${it.progress}),currentSize-(${it.currentSize}),totalSize-(${it.totalSize})\n")
                }
                .catch {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载异常：${it.errorMsg}\n")
                }.collect {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载完成：${it}\n")
                    "下载完成".toast()
                }
            Log.e("fanlyeee","")
        }
    }

    private fun downloadAppend(){
        scope.tryLaunch {
            val file = File(viewBinding.root.context.externalCacheDir,"append.apk")
            viewBinding.tvResult.append("---开始下载：${file.absolutePath}\n")
            progressDialog.show()
            if (file.exists() && MD5.getFileMd5(file).equals("d18663769baa2236c6805959ba782705",true)){
                file.delete()
            }
            RxHttp.get(DOWNLOAD_URL)
                .tag(DOWNLOAD_URL)
                .addParam("time",System.currentTimeMillis())
                .toDownload(file,true){
                    progressDialog.progress = it.progress
                    viewBinding.tvResult.append("progress-(${it.progress}),currentSize-(${it.currentSize}),totalSize-(${it.totalSize})\n")
                }
                .catch {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载异常：${it.errorMsg}\n")
                }.collect {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载完成：${it}\n")
                    Log.e("fanlyeee","")
                    "下载完成".toast()
                }
        }
    }

    private fun download10(){
        scope.tryLaunch {
            val factory = Android10DownloadFactory(requireContext(), "miaobo.apk")
            viewBinding.tvResult.append("---开始下载\n")
            progressDialog.show()
            RxHttp.get(DOWNLOAD_URL)
                .tag(DOWNLOAD_URL)
                .addParam("time",System.currentTimeMillis())
                .toDownload(factory){
                    progressDialog.progress = it.progress
                    viewBinding.tvResult.append("progress-(${it.progress}),currentSize-(${it.currentSize}),totalSize-(${it.totalSize})\n")
                }
                .catch {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载异常：${it.errorMsg}\n")
                }.collect {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载完成：${it}\n")
                    "下载完成".toast()
                }
        }
    }

    private fun download10Append(){
        scope.tryLaunch {
            val factory = Android10DownloadFactory(requireContext(), "miaobo.apk")
            viewBinding.tvResult.append("---开始下载\n")
            progressDialog.show()
            RxHttp.get(DOWNLOAD_URL)
                .tag(DOWNLOAD_URL)
                .addParam("time",System.currentTimeMillis())
                .toDownload(factory,true){
                    progressDialog.progress = it.progress
                    viewBinding.tvResult.append("progress-(${it.progress}),currentSize-(${it.currentSize}),totalSize-(${it.totalSize})\n")
                }
                .catch {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载异常：${it.errorMsg}\n")
                }.collect {
                    progressDialog.dismiss()
                    viewBinding.tvResult.append("---下载完成：${it}\n")
                    "下载完成".toast()
                }
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        scope.cancel()
    }
    private val scope = MainScope()
}

val Throwable.errorMsg: String
    get() {
        return if (this is UnknownHostException) { //网络异常
            if (!NetUtils.isNetConnected())
                "当前无网络，请检查你的网络设置"
            else
                "网络连接不可用，请稍后重试！"
        } else if (
            this is SocketTimeoutException  //okhttp全局设置超时
            || this is TimeoutException     //rxjava中的timeout方法超时
            || this is TimeoutCancellationException  //协程超时
        ) {
            "连接超时,请稍后再试"
        } else if (this is ConnectException) {
            "网络不给力，请稍候重试！"
        } else if (this is RxHttpResponseException) {               //请求失败异常
            "Http状态码异常 $message"
        } else {
            message ?: this.toString()
        }
    }